package com.example.mypc.myapplication;

import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener{

    private CustomVideoView vv;
    private LinearLayout ll_container;
    private ImageView pause;
    private ImageView next_left;
    private ImageView next_right;
    private int count=0;

    public static final int MEDIA_PLAY_TIME = 0X23;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case MEDIA_PLAY_TIME:
                    int n=  msg.arg1;
                    if (vv.isPlaying()) {
                        MyProgressBar pb = (MyProgressBar) ll_container.getChildAt(n);
                        pb.setProgress(vv.getCurrentPosition());
                        mPb_round.setProgress(vv.getCurrentPosition());
                    }
                    break;
            }
        }
    };
    private List<Uri> mList;
    private List<Integer> mDurations;
    private AutoRunTask mAutoRunTask;
    private RoundProgressBar mPb_round;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        initView();
        mList = initData();
        playViedeo(mList.get(0),0);
        mAutoRunTask = new AutoRunTask();
        //初始化圆形进度条
        mPb_round.setMax(mDurations.get(0));
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {
                if(count<mList.size()-1&&count>-1){
                    count++;
                    playViedeo(mList.get(count),count);
                    mPb_round.setMax(mDurations.get(count));
                }else {
                    Toast.makeText(VideoActivity.this,"锻炼完成",Toast.LENGTH_SHORT).show();
                    MyProgressBar pb= (MyProgressBar) ll_container.getChildAt(mList.size()-1);
                    pb.setProgress(mDurations.get(mList.size()-1));
                    count=mList.size()-1;
                }
            }
        });
    }

    private List<Uri> initData() {
        Uri parse1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_1);
        Uri parse2 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_2);
        Uri parse3 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        Uri parse4 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_1);
        Uri parse5 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.lalalala);
        Uri parse6 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        Uri parse7 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.lalalala);
        Uri parse8 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_2);
        Uri parse9 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        List<Uri> list=new ArrayList<>();
        list.add(parse1);
        list.add(parse2);
        list.add(parse3);
        list.add(parse4);
        list.add(parse5);
        list.add(parse6);
        list.add(parse7);
        list.add(parse8);
        list.add(parse9);
        //视频的各个长度
        mDurations = new ArrayList<>();
        MediaMetadataRetriever mmr=new MediaMetadataRetriever();
        for(int i=0;i<list.size();i++){
            mmr.setDataSource(this,list.get(i));
            // 播放时长单位为毫秒
            String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            mDurations.add(Integer.parseInt(duration));
            //初始化进度条
            MyProgressBar pb=new MyProgressBar(this);
            //set padding
            pb.setPadding(0);
            //set bacground color
            pb.setBgColor(Color.BLACK);
            //set progress color
            pb.setProgressColor(Color.GREEN);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0,ViewGroup.LayoutParams.MATCH_PARENT, mDurations.get(i)/100);
            if(i>0){
                params.setMargins(5,0,0,0);
            }
            pb.setLayoutParams(params);
            pb.setMax(mDurations.get(i));
            ll_container.addView(pb);
        }
        return list;
    }

    //播放视频
    private void playViedeo(Uri uri, final int count){
        vv.setVideoURI(uri);
        for(int n=1;n<=count;n++){
            MyProgressBar at = (MyProgressBar) ll_container.getChildAt(n-1);
            at.setProgress(mDurations.get(n-1));
        }
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                vv.start();
                mAutoRunTask.startRun();
            }
        });
    }
    private void initView() {
        vv = (CustomVideoView) findViewById(R.id.vv);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
        pause = (ImageView) findViewById(R.id.pause);
        next_left = (ImageView) findViewById(R.id.next_left);
        next_right = (ImageView) findViewById(R.id.next_right);
        mPb_round = (RoundProgressBar)findViewById(R.id.round_pb);
        pause.setOnClickListener(this);
        next_left.setOnClickListener(this);
        next_right.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //暂停
            case R.id.pause:
                if(vv.isPlaying()){
                    vv.pause();
                    mAutoRunTask.stopRun();
                }else {
                    vv.start();
                    mAutoRunTask.startRun();
                }
                break;
            //上一个视频
            case R.id.next_left:
                count--;
                if(count<0){
                    Toast.makeText(VideoActivity.this,"已经是第一条视频",Toast.LENGTH_SHORT).show();
                    count=0;
                    return;
                }
                MyProgressBar pb= (MyProgressBar) ll_container.getChildAt(count);
                MyProgressBar pb1= (MyProgressBar) ll_container.getChildAt(count+1);
                mPb_round.setProgress(0);
                mPb_round.setMax(mDurations.get(count));
                pb.setProgress(0);
                pb1.setProgress(0);
                playViedeo(mList.get(count),count);
                break;
            //下一个视频
            case R.id.next_right:
                count++;
                if(count>mList.size()-1){
                    Toast.makeText(VideoActivity.this,"已经是最后一条视频",Toast.LENGTH_SHORT).show();
                    count=mList.size()-1;
                    return;
                }
                mPb_round.setProgress(0);
                mPb_round.setMax(mDurations.get(count));
                playViedeo(mList.get(count),count);
                break;
        }
    }
    //自定跳转的线程任务
    class AutoRunTask implements Runnable {

        private int delayTime = 500;
        private boolean isStart = false;

        //开始线程任务
        public void startRun() {
            if (!isStart) {
                //关闭之前所有正在执行的任务
                mHandler.removeCallbacks(this);
                isStart = true;
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止线程的方法
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {

            //发送消息
            Message msg = Message.obtain();
            msg.what = MEDIA_PLAY_TIME;
            msg.arg1 = count;
            mHandler.sendMessage(msg);
            //递归调用自身,形成循环.
            mHandler.postDelayed(this, delayTime);
        }
    }
}
